//
//  LBVerticalRollView.m
//  LBVerticalRollView
//
//  Created by mac on 2024/6/6.
//

#import "LBVerticalRollView.h"

@interface LBVerticalRollView ()

@property (nonatomic, strong) UILabel *label1;
@property (nonatomic, strong) UILabel *label2;

@property (nonatomic, strong) NSArray *titleArray;

@property (nonatomic, assign) CGRect topRect;
@property (nonatomic, assign) CGRect currentRect;
@property (nonatomic, assign) CGRect bottomRect;

@property (nonatomic, assign) CGFloat duration;

@property (nonatomic, assign) NSInteger currentIndex;

@end

@implementation LBVerticalRollView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self setUpUI];
    }
    return self;
}

- (void)setUpUI
{
    self.topRect = CGRectMake(0, - 30, 300, 30);
    self.currentRect = CGRectMake(0, 0, 300, 30);
    self.bottomRect = CGRectMake(0, 30, 300, 30);
    [self addSubview:self.label1];
    [self addSubview:self.label2];
    self.label1.text = self.titleArray[0];
    self.label2.text = self.titleArray[1];
    self.clipsToBounds = YES;
}

- (void)startAnimationWithDuration:(CGFloat)duration
{
    self.duration = duration;
    [self changeAnimation];
}

- (void)changeAnimation
{
    CGRect rect1 = self.label1.frame;
    CGPoint point1 = rect1.origin;
    point1.y -= CGRectGetHeight(self.bounds);
    rect1.origin = point1;
    
    CGRect rect2 = self.label2.frame;
    CGPoint point2 = rect2.origin;
    point2.y -= CGRectGetHeight(self.bounds);
    rect2.origin = point2;
    
    self.currentIndex = (self.currentIndex + 1)%self.titleArray.count;
    NSString *crrentTitle = self.titleArray[self.currentIndex];
    [UIView animateWithDuration:0.5 animations:^{
        self.label1.frame = rect1;
        self.label2.frame = rect2;
    } completion:^(BOOL finished) {
        if (CGRectGetMinY(self.label1.frame) < - CGRectGetHeight(self.bounds) / 2) {
            self.label1.frame = self.bottomRect;
            self.label1.text = crrentTitle;
        } else {
            self.label2.frame = self.bottomRect;
            self.label2.text = crrentTitle;
        }
    }];
    [self performSelector:@selector(changeAnimation) withObject:nil afterDelay:3.5];
}

#pragma mark - lazy load

- (UILabel *)label1
{
    if (!_label1) {
        _label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 30)];
        _label1.textColor = [UIColor magentaColor];
        _label1.font = [UIFont systemFontOfSize:15];
    }
    return _label1;
}

- (UILabel *)label2
{
    if (!_label2) {
        _label2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, 300, 30)];
        _label2.textColor = [UIColor magentaColor];
        _label2.font = [UIFont systemFontOfSize:15];
    }
    return _label2;
}

- (NSArray *)titleArray
{
    if (!_titleArray) {
        _titleArray = @[@"这里是标题哈哈哈哈1", @"这里是标题哈哈哈哈2", @"这里是标题哈哈哈3", @"这里是标题哈哈哈4", @"这里是标题哈哈哈5"];
    }
    return _titleArray;
}

@end
